<template>
  <VDialog
    @close="handleClose"
    width="580px"
    :title="title"
    @save="save"
    :loading="loading"
  >
    <template #content>
      <el-form
        ref="formRef"
        label-position="top"
        :model="formValues"
        :rules="rules"
      >
        <el-form-item label="上级部门" prop="sub">
          <el-cascader
            style="width: 100%"
            v-model="formValues.sub"
            :options="options"
            :props="cascaderProps"
            @change="handleChange"
            filterable
          />
        </el-form-item>
        <el-form-item label="部门" prop="name">
          <el-input v-model="formValues.name" />
        </el-form-item>
      </el-form>
    </template>
  </VDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { reactive } from "vue";
import { detail, create, update } from "../api/index";
import { cascaderProps } from "../data";
const props = defineProps({
  title: { type: String, default: null },
  data: { type: Object, default: () => {} },
  options: { type: Object, default: () => {} },
});
watch(
  () => props.data,
  async (val) => {
    if (val.id) {
      const { data } = await detail({ id: val.id });
      for (let key in formValues) {
        formValues[key] = data[key];
      }
      formValues.sub = data.pid;
      formValues.pid = data.pid;
    } else {
      formValues.pid = val?.pid || null;
      formValues.sub = val?.pid || null;
    }
  }
);
const rules = reactive({
  sub: [{ required: true, message: "上级部门不能为空", trigger: "change" }],
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
});
const formValues = reactive({
  id: null,
  pid: null,
  name: null,
  sub: null,
});
const title = computed(() => {
  return props.data?.id ? '编辑' : '新增';
});
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const handleClose = async (refresh) => {
  for (let key in formValues) {
    formValues[key] = null;
  }
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
const handleChange = (value) => {
  if (Array.isArray(value)) {
    formValues.pid = value[value.length - 1];
  } else {
    formValues.pid = value;
  }
};
const formRef = ref();
const save = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true;
        const { code, message } = await (formValues?.id ? update : create)({
          ...formValues,
        });
        if (code !== 200) return ElMessage.warning(message);
        ElMessage.success("操作成功");
        handleClose(true);
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>
